package top.xiaoshuaila.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import top.xiaoshuaila.pojo.*;
import top.xiaoshuaila.service.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 小帅啦
 * @since 2021-05-01
 */
@RestController
@Api(tags = "员工管理")
@RequestMapping("/employee/basic")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IPoliticsStatusService politicsStatusService;

    @Autowired
    private IJoblevelService joblevelService;

    @Autowired
    private INationService nationService;

    @Autowired
    private IPositionService positionService;

    @Autowired
    private IDepartmentService departmentService;

    @ApiOperation("获取所有员工(分页)")
    @GetMapping("/")
    public RespPageBean getEmployee(@RequestParam(defaultValue = "1")Integer currentPage,
                                    @RequestParam(defaultValue = "10")Integer size,
                                    LocalDate[] beginDateScope,
                                    Employee employee) {
        return employeeService.getEmployeeByPage(currentPage,size,
                employee,beginDateScope);
    }

    @ApiOperation(("获取所有政治面貌"))
    @GetMapping("/politicsstatus")
    public List<PoliticsStatus>getAllPoliticsStatus(){
        return politicsStatusService.list();
    }

    @ApiOperation(("获取所有职称"))
    @GetMapping("/joblevels")
    public List<Joblevel>getAllJoblevels(){
        return joblevelService.list();
    }

    @ApiOperation("获取所有民族")
    @GetMapping("/nations")
    public List<Nation>getAllNations(){
        return nationService.list();
    }

    @ApiOperation("获取所有职位")
    @GetMapping("/positions")
    public List<Position>getAllPositions(){
        return positionService.list();
    }
    @ApiOperation("获取所有部门")
    @GetMapping("/deps")
    public List<Department>getAllDepartment(){
        return departmentService.getAllDepartments();
    }
    @ApiOperation("获取工号")
    @GetMapping("/maxWorkId")
    public RespBean maxWorkId(){
        return employeeService.maxWorkId();
    }

    @ApiOperation("添加员工")
    @PostMapping("/")
    public RespBean addEmp(@RequestBody Employee employee){
        return employeeService.addEmp(employee);
    }

    @ApiOperation("更新员工")
    @PutMapping("/")
    public RespBean updateEmp(@RequestBody Employee employee){
        if(employeeService.updateById(employee))
            return RespBean.success("更新成功!");
        return RespBean.error("更新失败!");
    }

    @ApiOperation("删除员工")
    @DeleteMapping("/{id}")
    public RespBean deleteEmp(@PathVariable Integer id){
        if(employeeService.removeById(id))
            return RespBean.success("删除成功!");
        return RespBean.error("删除失败!");
    }

    @ApiOperation(value = "导出员工数据")
    @GetMapping(value = "/export",produces = "application/octet-stream")
    public void exportEmployee(HttpServletResponse response){
        //首先将要导出的数据查出为list集合
        List<Employee> list = employeeService.getEmployee(null);
        //告别设置excel的标题名,sheet名和版本
        ExportParams params=new ExportParams("员工表","员工表",
                ExcelType.HSSF);
        //使用依赖的导出工具类设置params,对应的类class,和数据
        Workbook workbook = ExcelExportUtil.exportExcel(params,
                Employee.class, list);
        //设置输出流
        ServletOutputStream out=null;
        try {
            //设置excel响应头信息
            response.setHeader("content-type","application/octet-stream");
            //设置UTF-8防止中文乱码
            response.setHeader("content-disposition","attachment" +
                    ";filename="+ URLEncoder.encode("员工表.xls","UTF" +
                    "-8"));
            out=response.getOutputStream();
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭输出流
            if(null!=out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @ApiOperation("导入员工数据")
    @PostMapping("/import")
    public RespBean importEmployee(@ApiParam(value="文件",required=
            true)@RequestPart("file") MultipartFile file){
        ImportParams params=new ImportParams();
        //告诉第一行为标题
        params.setTitleRows(1);
        List<Nation>nationList=nationService.list();
        List<PoliticsStatus>politicsStatusList=
                politicsStatusService.list();
        List<Department>departmentList=departmentService.list();
        List<Joblevel>joblevelList=joblevelService.list();
        List<Position>positionList=positionService.list();
        try {
            //利用依赖的工具类将文件转换为list集合
            List<Employee> list =
                    ExcelImportUtil.importExcel(file.getInputStream(),
                    Employee.class, params);
            for (Employee e:list
                 ) {
                e.setNationId(
                        nationList.get(
                                nationList.indexOf(new Nation(e.getNation().getName()))
                        ).getId()
                );
                e.setPoliticId(
                        politicsStatusList.get(
                                politicsStatusList.indexOf(new PoliticsStatus(e.getPoliticsStatus().getName()))
                        ).getId()
                );
                e.setDepartmentId(
                        departmentList.get(
                                departmentList.indexOf(new Department(e.getDepartment().getName()))
                        ).getId()
                );
                e.setJobLevelId(
                        joblevelList.get(
                                joblevelList.indexOf(new Joblevel(e.getJoblevel().getName()))
                        ).getId()
                );
                e.setPosId(
                        positionList.get(
                                positionList.indexOf(new Position(e.getPosition().getName()))
                        ).getId()
                );
            }
            //正常将list保存导数据库
            if(employeeService.saveBatch(list))
                return RespBean.success("添加成功!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("导入失败!");
    }
}
